<template>
  <div class="spouse-join">
    <el-card>
      <template #header>
        <span>夫妻投靠</span>
      </template>
      
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <!-- 申请人信息 -->
        <el-divider content-position="left">申请人信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="申请人身份证号" prop="applicantIdCard">
              <el-input
                v-model="form.applicantIdCard"
                placeholder="请输入申请人身份证号"
                maxlength="18"
                show-word-limit
                :loading="applicantLoading"
                @input="handleApplicantIdCardInput"
                @blur="handleApplicantIdCardBlur"
              >
                <template #suffix>
                  <el-icon v-if="applicantLoading" class="is-loading"><Loading /></el-icon>
                  <el-icon v-else-if="applicantInfo.name" color="#67c23a"><CircleCheck /></el-icon>
                  <el-icon v-else-if="form.applicantIdCard && form.applicantIdCard.length === 18 && !validateIdCard(form.applicantIdCard)" color="#f56c6c"><CircleClose /></el-icon>
                </template>
              </el-input>
              <div v-if="applicantInfo.name" class="person-info-display">
                <el-tag type="success" size="small">
                  <el-icon><User /></el-icon>
                  {{ applicantInfo.name }} - {{ applicantInfo.phone || '无电话' }}
                </el-tag>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 被投靠人信息 -->
        <el-divider content-position="left">被投靠人信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="被投靠人身份证号" prop="targetIdCard">
              <el-input
                v-model="form.targetIdCard"
                placeholder="请输入被投靠人身份证号"
                maxlength="18"
                show-word-limit
                :loading="targetLoading"
                @input="handleTargetIdCardInput"
                @blur="handleTargetIdCardBlur"
              >
                <template #suffix>
                  <el-icon v-if="targetLoading" class="is-loading"><Loading /></el-icon>
                  <el-icon v-else-if="targetInfo.name" color="#67c23a"><CircleCheck /></el-icon>
                  <el-icon v-else-if="form.targetIdCard && form.targetIdCard.length === 18 && !validateIdCard(form.targetIdCard)" color="#f56c6c"><CircleClose /></el-icon>
                </template>
              </el-input>
              <div v-if="targetInfo.name" class="person-info-display">
                <el-tag type="success" size="small">
                  <el-icon><User /></el-icon>
                  {{ targetInfo.name }} - {{ targetInfo.phone || '无电话' }}
                </el-tag>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 投靠信息 -->
        <el-divider content-position="left">投靠信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="与被投靠人关系" prop="relationship">
              <el-select v-model="form.relationship" placeholder="请选择关系" style="width: 100%">
                <el-option label="配偶" value="配偶" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="投靠原因" prop="transferReason">
              <el-select v-model="form.transferReason" placeholder="请选择投靠原因" style="width: 100%">
                <el-option label="夫妻投靠" value="夫妻投靠" />
                <el-option label="工作调动" value="工作调动" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">提交申请</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { CircleCheck, CircleClose, Loading, User } from '@element-plus/icons-vue'
import axios from 'axios'
import { API_BASE_URL } from '@/config/api.js'

// 防抖延迟时间
const DEBOUNCE_DELAY = 800

// 表单引用和状态
const formRef = ref()
const loading = ref(false)
const submitting = ref(false)

// 申请人相关状态
const applicantLoading = ref(false)
const applicantInfo = ref({})
const applicantDebounceTimer = ref(null)

// 被投靠人相关状态
const targetLoading = ref(false)
const targetInfo = ref({})
const targetDebounceTimer = ref(null)

// 表单数据
const form = reactive({
  applicantIdCard: '',
  targetIdCard: '',
  relationship: '配偶',
  transferReason: ''
})

// 表单验证规则
const rules = {
  applicantIdCard: [
    { required: true, message: '请输入申请人身份证号', trigger: 'blur' },
    { 
      pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, 
      message: '请输入正确的身份证号码', 
      trigger: 'blur' 
    }
  ],
  targetIdCard: [
    { required: true, message: '请输入被投靠人身份证号', trigger: 'blur' },
    { 
      pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, 
      message: '请输入正确的身份证号码', 
      trigger: 'blur' 
    }
  ],
  relationship: [
    { required: true, message: '请选择与被投靠人的关系', trigger: 'change' }
  ],
  transferReason: [
    { required: true, message: '请选择投靠原因', trigger: 'change' }
  ]
}

// 身份证号验证函数
const validateIdCard = (idCard) => {
  const pattern = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
  return pattern.test(idCard)
}

// 根据身份证号获取人员信息
const getPersonByIdCard = async (idCard) => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get(`${API_BASE_URL}/person/getByIdCard`, {
      params: { idCard },
      headers: { token }
    })
    
    if (response.data.status === 200) {
      return response.data.data
    }
    return null
  } catch (error) {
    console.error('根据身份证号获取人员信息失败:', error)
    return null
  }
}

// 处理申请人身份证号输入（防抖）
const handleApplicantIdCardInput = (value) => {
  // 清除之前的定时器
  if (applicantDebounceTimer.value) {
    clearTimeout(applicantDebounceTimer.value)
  }
  
  // 清空之前的信息
  applicantInfo.value = {}
  
  // 如果输入为空或长度不够，直接返回
  if (!value || value.length < 18) {
    return
  }
  
  // 验证身份证号格式
  if (!validateIdCard(value)) {
    // 如果格式不正确且长度为18位，显示错误提示
    if (value.length === 18) {
      ElMessage.error('申请人身份证号格式不正确，请检查后重新输入')
    }
    return
  }
  
  // 设置防抖定时器（800ms）
  applicantDebounceTimer.value = setTimeout(async () => {
    await fetchApplicantInfo(value)
  }, DEBOUNCE_DELAY)
}

// 处理被投靠人身份证号输入（防抖）
const handleTargetIdCardInput = (value) => {
  // 清除之前的定时器
  if (targetDebounceTimer.value) {
    clearTimeout(targetDebounceTimer.value)
  }
  
  // 清空之前的信息
  targetInfo.value = {}
  
  // 如果输入为空或长度不够，直接返回
  if (!value || value.length < 18) {
    return
  }
  
  // 验证身份证号格式
  if (!validateIdCard(value)) {
    // 如果格式不正确且长度为18位，显示错误提示
    if (value.length === 18) {
      ElMessage.error('被投靠人身份证号格式不正确，请检查后重新输入')
    }
    return
  }
  
  // 设置防抖定时器（800ms）
  targetDebounceTimer.value = setTimeout(async () => {
    await fetchTargetInfo(value)
  }, DEBOUNCE_DELAY)
}

// 处理申请人身份证号失焦
const handleApplicantIdCardBlur = () => {
  const value = form.applicantIdCard
  if (value && value.length === 18 && validateIdCard(value) && !applicantInfo.value.name) {
    // 如果身份证号完整且格式正确，但还没有获取到信息，立即获取
    fetchApplicantInfo(value)
  }
}

// 处理被投靠人身份证号失焦
const handleTargetIdCardBlur = () => {
  const value = form.targetIdCard
  if (value && value.length === 18 && validateIdCard(value) && !targetInfo.value.name) {
    // 如果身份证号完整且格式正确，但还没有获取到信息，立即获取
    fetchTargetInfo(value)
  }
}

// 获取申请人信息
const fetchApplicantInfo = async (idCard) => {
  // 防止重复请求
  if (applicantLoading.value) return
  
  applicantLoading.value = true
  try {
    const person = await getPersonByIdCard(idCard)
    
    // 检查身份证号是否还匹配（防止异步竞态条件）
    if (form.applicantIdCard !== idCard) {
      return
    }
    
    if (person) {
      // 设置申请人信息
      applicantInfo.value = person
      ElMessage.success(`已找到申请人信息：${person.name}`)
    } else {
      ElMessage.error('未找到该身份证号对应的人员信息，请确认身份证号是否正确')
    }
  } catch (error) {
    // 检查身份证号是否还匹配
    if (form.applicantIdCard !== idCard) {
      return
    }
    
    console.error('获取申请人信息失败:', error)
    if (error.response?.status === 404) {
      ElMessage.error('未找到该身份证号对应的人员信息')
    } else if (error.response?.status === 400) {
      ElMessage.error('身份证号格式不正确')
    } else {
      ElMessage.error('获取申请人信息失败，请稍后重试')
    }
  } finally {
    applicantLoading.value = false
  }
}

// 获取被投靠人信息
const fetchTargetInfo = async (idCard) => {
  // 防止重复请求
  if (targetLoading.value) return
  
  targetLoading.value = true
  try {
    const person = await getPersonByIdCard(idCard)
    
    // 检查身份证号是否还匹配（防止异步竞态条件）
    if (form.targetIdCard !== idCard) {
      return
    }
    
    if (person) {
      // 设置被投靠人信息
      targetInfo.value = person
      ElMessage.success(`已找到被投靠人信息：${person.name}`)
    } else {
      ElMessage.error('未找到该身份证号对应的人员信息，请确认身份证号是否正确')
    }
  } catch (error) {
    // 检查身份证号是否还匹配
    if (form.targetIdCard !== idCard) {
      return
    }
    
    console.error('获取被投靠人信息失败:', error)
    if (error.response?.status === 404) {
      ElMessage.error('未找到该身份证号对应的人员信息')
    } else if (error.response?.status === 400) {
      ElMessage.error('身份证号格式不正确')
    } else {
      ElMessage.error('获取被投靠人信息失败，请稍后重试')
    }
  } finally {
    targetLoading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    // 验证是否已获取到人员信息
    if (!applicantInfo.value.name) {
      ElMessage.error('请先输入有效的申请人身份证号并获取人员信息')
      return
    }
    
    if (!targetInfo.value.name) {
      ElMessage.error('请先输入有效的被投靠人身份证号并获取人员信息')
      return
    }
    
    // 验证申请人和被投靠人不能是同一人
    if (form.applicantIdCard === form.targetIdCard) {
      ElMessage.error('申请人和被投靠人不能是同一人')
      return
    }
    
    submitting.value = true
    
    const submitData = {
      applicantIdCard: form.applicantIdCard,
      targetIdCard: form.targetIdCard,
      relationship: form.relationship,
      transferReason: form.transferReason
    }
    
    console.log('提交夫妻投靠申请数据:', submitData)
    
    const token = localStorage.getItem('token')
    const response = await axios.post(`${API_BASE_URL}/household/applyTransfer`, submitData, {
      headers: {
        'token': token,
        'Content-Type': 'application/json'
      }
    })
    
    console.log('夫妻投靠申请响应:', response.data)
    
    const result = response.data
    if (result.status === 200) {
      ElMessage.success(result.msg || '夫妻投靠申请提交成功')
      handleReset()
    } else {
      ElMessage.error(result.msg || '夫妻投靠申请提交失败')
    }
    
  } catch (error) {
    console.error('夫妻投靠申请请求出错:', error)
    
    if (error.response) {
      const errorData = error.response.data
      if (errorData && errorData.msg) {
        ElMessage.error(errorData.msg)
      } else {
        ElMessage.error(`请求失败: ${error.response.status}`)
      }
    } else if (error.request) {
      ElMessage.error('网络请求失败，请检查网络连接')
    } else {
      ElMessage.error('请求配置错误')
    }
  } finally {
    submitting.value = false
  }
}

// 重置表单
const handleReset = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  // 清空所有数据
  Object.assign(form, {
    applicantIdCard: '',
    targetIdCard: '',
    relationship: '配偶',
    transferReason: ''
  })
  
  // 清空人员信息
  applicantInfo.value = {}
  targetInfo.value = {}
  
  // 重置加载状态
  applicantLoading.value = false
  targetLoading.value = false
  submitting.value = false
  
  // 清除防抖定时器
  if (applicantDebounceTimer.value) {
    clearTimeout(applicantDebounceTimer.value)
    applicantDebounceTimer.value = null
  }
  if (targetDebounceTimer.value) {
    clearTimeout(targetDebounceTimer.value)
    targetDebounceTimer.value = null
  }
}
</script>

<style lang="scss" scoped>
.spouse-join {
  .el-form {
    max-width: 800px;
  }
  
  .person-info-display {
    margin-top: 8px;
    
    .el-tag {
      display: inline-flex;
      align-items: center;
      gap: 4px;
    }
  }
  
  .el-divider {
    margin: 24px 0 16px 0;
    
    .el-divider__text {
      font-weight: 600;
      color: #409eff;
    }
  }
  
  .el-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  .el-input {
    .is-loading {
      animation: rotating 2s linear infinite;
    }
  }
  
  @keyframes rotating {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
}
</style>